package com.dong.c08_netty_http;

import com.sun.corba.se.impl.ior.ByteBuffer;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.net.URI;

/**
 * <h1></h1>
 * {@link HttpObject} 客户端和服务器端相互通信的数据被封装的对象
 * @author : dzj
 * @create: 2021-03-08 09:06
 */
public class TestServerHandler extends SimpleChannelInboundHandler<HttpObject> {
    /**
     * 读取客户端数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {
        if(msg instanceof HttpRequest) {
            //一下两个都是独立的,  不共享
            System.out.println("pipeline: "+ctx.pipeline()+", handler: "+this);



            System.out.println("msg 类型: "+msg.getClass());
            System.out.println("客户端地址: "+ctx.channel().remoteAddress());

            HttpRequest request = (HttpRequest) msg;
            //获取uri , 过滤指定资源
            URI uri = new URI(request.uri());
            if("/favicon.ico".equals(uri.getPath())) {
                System.out.println(" 请求了 favicon.ico  , 不做响应");
                return;
            }

            ByteBuf byteBuf = Unpooled.copiedBuffer("Hello , 我是服务器", CharsetUtil.UTF_8);
            //狗仔一个http的响应,即httpResponse
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/html; charset=utf-8");
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH,byteBuf.readableBytes());
            ctx.writeAndFlush(response);
        }
    }
}
